using System;
using System.Collections.Generic;
using System.Text;
using SubSonic;

using Impact.Model.Objects;

namespace Impact.Model.Service
{

    /// <summary>
    /// data service that provides category data
    /// </summary>
    public class CategoryService : ICategoryService
    {
        #region ICategoryService Members

        /// <summary>
        /// Retrieve the item from the datastore using the given ID
        /// </summary>
        public ArticleCategory FetchByID( int categoryId )
        {
            return ArticleCategory.FetchByID( categoryId );
        }

        /// <summary>
        /// Retrieve the item from the datastore using the given key
        /// </summary>
        public ArticleCategory FetchByKey( string categoryKey )
        {
            ArticleCategory category = new ArticleCategory();
            category.LoadByParam( ArticleCategory.Columns.NameKey, categoryKey );
            return category;
        }

        /// <summary>
        /// Retrieve all items from the datastore
        /// </summary>
        public ArticleCategoryCollection FetchAll( bool onlyVisible )
        {
            ArticleCategoryCollection categories = new ArticleCategoryCollection()
                .OrderByAsc( ArticleCategory.Columns.Name );
            if ( onlyVisible )
            {
                categories.Where( ArticleCategory.Columns.MenuVisible, 1 );
            }
            return categories.Load();
        }

        /// <summary>
        /// Save the given item to the datastore and logs the given user ID as the modifier
        /// </summary>
        public void Save( ArticleCategory category, Guid userId )
        {
            category.Save( userId );
        }

        /// <summary>
        /// Removes the given category from the datastore
        /// </summary>
        public void Remove( int categoryId )
        {
            ArticleCategory.Delete( categoryId );
        }

        /// <summary>
        /// retrieve the number of articles in the given category
        /// </summary>
        public int GetCategoryArticleCount( int categoryId )
        {
            QueryCommand qc = new QueryCommand( "SELECT COUNT(ArticleId) FROM impact_Articles WHERE CategoryId=@categoryId", Databases.ImpactProvider );
            qc.AddParameter( "@categoryId", categoryId, System.Data.DbType.Int32 );
            object result = DataService.ExecuteScalar( qc );
            return Convert.ToInt32( result );
        }

        #endregion
    }
}
